import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:rtm_test_app/sender.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String message = "";

  void _sendUDP() {
    setState(() {});
    // sendMulticastMessage(message);
    // sendBroadcastMessage(message);
    sendVideo("assets/video.mp4");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // startUdpSender();
    // startUdpBroadcaster();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
          child: Column(
        children: [
          Container(
            width: 400,
            alignment: Alignment.topCenter,
            child: Text("填写要发送的内容"),
          ),
          Container(
            width: 400,
            alignment: Alignment.topCenter,
            child: TextField(
              decoration: InputDecoration(),
              onChanged: (string) {
                message = string;
              },
            ),
          )
        ],
      )),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendUDP,
        tooltip: 'Increment',
        child: const Icon(Icons.send),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  final multicastAddress = '224.123.1.1'; // Replace with your multicast address

  Future<int> startUdpSender() async {
    // Multicast address and port

    try {
      // Create a RawDatagramSocket
      final RawDatagramSocket socket = await RawDatagramSocket.bind(
          InternetAddress.anyIPv4, 0,
          reuseAddress: true, ttl: 10);

      // Enable multicast on the socket
      socket.joinMulticast(InternetAddress(multicastAddress));

      // Store the socket for later use
      _udpSocket = socket;

      print('UDP multicast socket created');
    } catch (e) {
      print('Failed to create UDP socket: $e');
    }
    return Future.value(1);
  }

  RawDatagramSocket? _udpSocket;

  void sendMulticastMessage(String message) {
    startUdpSender().then((i) {
      if (_udpSocket != null) {
        // Multicast address and port
        const port = 30001; // Replace with your port

        // Convert the message to bytes
        // final Uint8List data = Uint8List.fromList(message.codeUnits);

        // Send the message
        var result = _udpSocket!
            .send(message.codeUnits, InternetAddress(multicastAddress), port);
        print('Sent UDP multicast: $message,result=$result');
        _udpSocket?.close();
      } else {
        print('UDP socket is not initialized');
      }
    });
  }

  RawDatagramSocket? _udpBroadcastSocket;

  Future<int> startUdpBroadcaster() async {
    // Broadcast address and port
    const broadcastAddress = '255.255.255.255'; // Broadcast address
    const port = 44444; // Replace with your port

    try {
      // Create a RawDatagramSocket
      final RawDatagramSocket socket = await RawDatagramSocket.bind(
        InternetAddress.anyIPv4,
        0, // Bind to any available port
        reuseAddress: true,
      );

      // Enable broadcast on the socket
      socket.broadcastEnabled = true;

      // Store the socket for later use
      _udpBroadcastSocket = socket;

      print('UDP broadcast socket created');
    } catch (e) {
      print('Failed to create UDP socket: $e');
    }
    return Future.value(1);
  }

  void sendBroadcastMessage(String message) {
    startUdpBroadcaster().then((onValue) {
      if (_udpBroadcastSocket != null) {
        // Broadcast address and port
        const broadcastAddress = '255.255.255.255'; // Broadcast address
        const port = 44444; // Replace with your port

        // Convert the message to bytes
        final Uint8List data = Uint8List.fromList(message.codeUnits);

        // Send the message
        int bytesSent = _udpBroadcastSocket!
            .send(data, InternetAddress(broadcastAddress), port);
        if (bytesSent > 0) {
          print('Sent UDP broadcast: $message');
        } else {
          print('Failed to send UDP broadcast message');
        }
        _udpBroadcastSocket?.close();
      } else {
        print('UDP socket is not initialized');
      }
    });
  }
}
